import type { AutomationRequest } from '../services/automation-service'
// 自动化预约相关的IPC处理程序
import { BrowserWindow, ipcMain } from 'electron'
import { getLogger } from '../logger/index'
import { getAutomationService } from '../services/automation-service'

let logger: any = null
const automationService = getAutomationService()

// 获取日志实例（延迟初始化）
function getLoggerInstance() {
  if (!logger) {
    try {
      logger = getLogger()
    }
    catch {
      // 如果日志系统未初始化，使用console作为备选
      logger = {
        info: console.log,
        warn: console.warn,
        error: console.error,
      }
    }
  }
  return logger
}

/**
 * 注册自动化预约相关的IPC处理程序
 */
export function registerAutomationHandlers() {
  // 开始自动化预约
  ipcMain.handle('automation:start', async (event, request: AutomationRequest) => {
    const loggerInstance = getLoggerInstance()
    try {
      loggerInstance.info('收到自动化预约请求', {
        appointmentCount: request.appointments.length,
        options: request.options,
      })

      // 设置日志回调，将日志发送到前端
      automationService.setLogCallback((level: string, message: string) => {
        const webContents = BrowserWindow.fromWebContents(event.sender)
        if (webContents && !webContents.isDestroyed()) {
          webContents.webContents.send('automation:log', level, message)
        }
      })

      const result = await automationService.startAutomation(request)

      loggerInstance.info('自动化预约请求处理完成', {
        success: result.success,
        resultsCount: result.results?.length || 0,
      })

      return result
    }
    catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error)
      loggerInstance.error('处理自动化预约请求失败', { error: errorMsg })

      return {
        success: false,
        error: errorMsg,
      }
    }
  })

  // 停止自动化预约
  ipcMain.handle('automation:stop', async () => {
    const loggerInstance = getLoggerInstance()
    try {
      loggerInstance.info('收到停止自动化预约请求')
      const result = await automationService.stopAutomation()

      loggerInstance.info('停止自动化预约请求处理完成', { success: result.success })
      return result
    }
    catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error)
      loggerInstance.error('处理停止自动化预约请求失败', { error: errorMsg })

      return {
        success: false,
        error: errorMsg,
      }
    }
  })

  // 获取自动化状态
  ipcMain.handle('automation:status', () => {
    const loggerInstance = getLoggerInstance()
    try {
      return {
        success: true,
        data: automationService.getStatus(),
      }
    }
    catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error)
      loggerInstance.error('获取自动化状态失败', { error: errorMsg })

      return {
        success: false,
        error: errorMsg,
      }
    }
  })

  getLoggerInstance().info('自动化预约IPC处理程序已注册')
}
